using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;

namespace pdogs.adventuresinrest.Features.AdventuresInREST
{
// ReSharper disable InconsistentNaming

	/// <summary>
	/// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
	/// </summary>
	/// <remarks>
	/// The GUID attached to this class may be used during packaging and should not be modified.
	/// </remarks>
	[Guid("e8556d53-ead9-4096-8e2c-e623484e84ef")]
	public class AdventuresInRESTEventReceiver : SPFeatureReceiver
	{
//		public override void FeatureActivated(SPFeatureReceiverProperties properties)
//		{
//		}

		/// <summary>
		/// Occurs when a Feature is deactivated.
		/// </summary>
		/// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties" /> object that represents the properties of the event.</param>
		public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
		{
			var web = properties.Feature.Parent as SPWeb;
			if (web == null) return;
			var saveAuu = web.AllowUnsafeUpdates;
			try
			{
				web.AllowUnsafeUpdates = true;

				var sa = web.Folders.Cast<SPFolder>().FirstOrDefault(l => l.Name == "SiteAssets");
				var sp = web.Folders.Cast<SPFolder>().FirstOrDefault(l => l.Name == "SitePages");

				var folder = sa != null ? sa.SubFolders.Cast<SPFolder>().FirstOrDefault(f => f.Name == "AIR") : null;
				if (folder != null)
					folder.Delete();
				folder = sp != null ? sp.SubFolders.Cast<SPFolder>().FirstOrDefault(f => f.Name == "AIR") : null;
				if (folder != null)
					folder.Delete();
			}
			finally
			{
				web.AllowUnsafeUpdates = saveAuu;
			}
		}

//		public override void FeatureInstalled(SPFeatureReceiverProperties properties)
//		{
//		}
//
//		public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
//		{
//		}
//
//		public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
//		{
//		}
	}
}
